package cn.wolfcode.transfer.util;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateBetween;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.wolfcode.transfer.domain.Log;
import cn.wolfcode.transfer.service.ILogService;
import cn.wolfcode.transfer.service.impl.LogServiceImpl;
import com.alibaba.fastjson.JSON;
import jdk.jshell.MethodSnippet;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@Component //把当前类注入到spring容器中
@Aspect    //把当前类标识为一个切面供容器读取
public class AopConfig {

    @Autowired
    public ILogService service;
    /**
     * 指定切入点
     * 对贴有自定义注解@RequiredPermission的方法，进行切面
     */
    @Pointcut("@annotation(cn.wolfcode.transfer.util.RequiredPermission)")
    private void useMethod() {

    }

    /**
     * 对切入点进行增强
     */
    @Around(value = "useMethod()")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object target = proceedingJoinPoint.getTarget();
        Class<?> aClass = target.getClass();
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method declaredMethod = aClass.getDeclaredMethod(signature.getName(), signature.getParameterTypes());
        Date date = new Date();
        //获取方法上注解
        RequiredPermission annotation = declaredMethod.getAnnotation(RequiredPermission.class);
        System.out.println();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> strings = parameterMap.keySet();
        String str = "{";
        for (String string : strings) {
            String[] strings1 = parameterMap.get(string);
            for (String s : strings1) {
                str += string + ":" + s + ",";
            }
        }
        if (str.length()-1 != 0) {
           str = str.substring(0, str.length() - 1) + "}";
        }


        Log log = new Log();
        //执行处理方法（执行控制器中的方法）
        Object result = null;
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Exception throwable) {
            log.setOperatingResult(false);
            log.setMsg(throwable.getMessage());
            throw throwable;
        }finally {
            log.setExpression(annotation.expression());
            log.setIp("0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip);
            log.setName(annotation.name());
            log.setUser(UserContext.getCurrentUser());
            log.setExecutionTime(date);
            log.setOperationTime(DateUtil.formatBetween(date, new Date(), BetweenFormater.Level.MILLISECOND));
            log.setRequiredParameter(str);
            service.save(log);
        }
        //result是方法的返回值，直接return回去就会返回给springmvc处理
        return result;
    }
}